<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.merchant_desk_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-button
          type="text"
          size="small"
          @click.stop="handleQrCode(row)"
        >二维码
        </el-button>
      </template>
      <template slot-scope="{row}"
                slot="deskCategoryId">
        <span
          v-if="row.deskCategoryName.split(',').length > 0 && row.deskCategoryName !== ''"
          v-for="name in row.deskCategoryName.split(',')"
        >
          <el-tag
            size="small"
            type="success"
          >{{name}}</el-tag>&nbsp;
        </span>
      </template>
    </avue-crud>
    <el-dialog
      title="桌台二维码"
      :visible.sync="dialogVisible"
      width="30%">
      <div style="margin-left: 40px">
        <p>点击确定即可下载桌台二维码！</p>
        <vue-qr ref="Qrcode"
                :text="qrCodeObject.text"
                :logoSrc="qrCodeObject.logo"
                :logoMargin=2
        ></vue-qr>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="downloadQrCode">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/merchant/merchant_desk";
  import {getSelect as getCategoryList} from "@/api/merchant/merchant_desk_category";
  import {mapGetters} from "vuex";
  import website from "@/config/website";
  import VueQr from 'vue-qr'

  export default {
    components: { VueQr },
    data() {
      return {
        dialogVisible: false,
        qrCodeObject: {
          text: "",
          logo: require("../../../public/favicon.png"),
          imageName: ""
        },
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          column: [
            {
              label: "桌台类型",
              prop: "deskCategoryId",
              multiple: false,
              type: "select",
              dicData: [],
              props: {
                label: "name",
                value: "id"
              },
              slot: true,
              rules: [{
                required: true,
                message: "请选择桌台类型",
                trigger: "blur"
              }]
            },
            {
              label: "所属店铺",
              prop: "tenantId",
              type: "tree",
              dicUrl: "/api/blade-system/tenant/select-all",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: website.tenantMode,
              span: 24,
              props: {
                label: "tenantName",
                value: "tenantId"
              }
            },
            {
              label: "桌名",
              prop: "name",
              rules: [{
                required: true,
                message: "请输入桌名",
                trigger: "blur"
              }]
            },
            {
              label: "桌编号",
              prop: "code",
              rules: [{
                required: true,
                message: "请输入桌编号",
                trigger: "blur"
              }]
            },
            {
              label: "排序",
              prop: "sort",
              rules: [{
                required: true,
                message: "请输入排序",
                trigger: "blur"
              }]
            }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.merchant_desk_add, false),
          viewBtn: this.vaildData(this.permission.merchant_desk_view, false),
          delBtn: this.vaildData(this.permission.merchant_desk_delete, false),
          editBtn: this.vaildData(this.permission.merchant_desk_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
        getCategoryList().then(res => {
          const column = this.findObject(this.option.column, "deskCategoryId");
          column.dicData = res.data.data;
        });
      },
      handleQrCode(row) {
        this.dialogVisible = true;
        this.qrCodeObject.text = 'tenantId=' + row.tenantId + '&deskId=' + row.id + '&deskCode=' + row.code;
        this.qrCodeObject.imageName = row.$tenantId + '-桌台-' + row.code;
      },
      downloadQrCode () {
        const iconUrl = this.$refs.Qrcode.$el.src
        let a = document.createElement('a')
        let event = new MouseEvent('click')
        a.download = this.qrCodeObject.imageName;
        a.href = iconUrl
        a.dispatchEvent(event)
        this.dialogVisible = false;
      }
    }
  };
</script>

<style>
</style>
